﻿using System;
using System.Collections.Generic;

namespace EnterpriseLibraryExtensions.Services.Mapping
{
    internal class CollectionElementTypeExtractor : ICollectionElementTypeExtractor
    {
        public Type GetElementType(Type sourceType)
        {
            Type elementType = sourceType.GetElementType();

            if (elementType == null)
                elementType = GetEnumerableType(sourceType);

            if (elementType == null)
                elementType = GetListType(sourceType);

            return elementType;
        }

        private static Type GetListType(Type listType)
        {
            if (listType.IsGenericType && listType.GetGenericTypeDefinition() == typeof(List<>))
            {
                Type[] listTypes = listType.GetGenericArguments();
                return listTypes[0];
            }

            return null;
        }

        private static Type GetEnumerableType(Type listType)
        {
            if (listType.IsGenericType && listType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
            {
                Type[] listTypes = listType.GetGenericArguments();
                return listTypes[0];
            }

            return null;
        }
    }
}
